package study_thread;

import java.util.concurrent.Semaphore;

/**
 * 限流
 *
 * @author: 李德才
 * @description:
 * @create: 2020-12-12 20:12
 **/
public class Test_Semaphore {

    public static void main(String[] args) {
        /**
         * 只允许一个线程执行
         */
        Semaphore semaphore = new Semaphore(1, true);
        new Thread(() -> {
            try {
                semaphore.acquire();
                System.out.println("111111");
                Thread.sleep(2000);
                System.out.println("1111111");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release();
            }
        }).start();
        new Thread(() -> {
            try {
                semaphore.acquire();
                System.out.println("2222222");
                Thread.sleep(2000);
                System.out.println("2222222");
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(() -> {
            try {
                semaphore.acquire();
                System.out.println("3333333");
                Thread.sleep(2000);
                System.out.println("3333333");
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}
